package com.vhuomai.wechat.controller;

import com.quanyue.auto.util.ServiceResult;
import com.quanyue.auto.util.http.Http;
import com.quanyue.auto.web.Scope;
import com.vhuomai.system.constant.UserRole;
import com.vhuomai.wechat.constant.MaterialType;
import com.vhuomai.wechat.dto.MessageSend;
import com.vhuomai.weixin.common.api.WxConsts;
import com.vhuomai.weixin.common.bean.result.WxMediaUploadResult;
import com.vhuomai.weixin.common.exception.WxErrorException;
import com.vhuomai.weixin.mp.api.WxMpService;
import com.vhuomai.weixin.mp.bean.WxMpMassNews;
import com.vhuomai.weixin.mp.bean.WxMpMassTagMessage;
import com.vhuomai.weixin.mp.bean.WxMpMassVideo;
import com.vhuomai.weixin.mp.bean.material.WxMpMaterialNews;
import com.vhuomai.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;
import com.vhuomai.weixin.mp.bean.result.WxMpMassSendResult;
import com.vhuomai.weixin.mp.bean.result.WxMpMassUploadResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.Response;
import org.apache.tika.mime.MimeTypeException;
import org.apache.tika.mime.MimeTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author harris
 */
@Api(tags = "微信公众号消息")
@RestController
@RequestMapping("/api")
@Scope(role = UserRole.MANAGER)
public class WxMessageController {
    
    @Autowired
    private WxMpService wxMpService;
    
    @ApiOperation(value = "消息发送")
    @PostMapping(value = "/wx/message/send", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult<Boolean> messageSend(@RequestBody MessageSend messageSend) throws WxErrorException, IOException, MimeTypeException {
        WxMpMassTagMessage massMessage = new WxMpMassTagMessage();
        if (messageSend.getType() == MaterialType.TEXT) {
            massMessage.setMsgType(WxConsts.MASS_MSG_TEXT);
            massMessage.setContent(messageSend.getContent());
        } else if (messageSend.getType() == MaterialType.IMAGE) {
            massMessage.setMsgType(WxConsts.MASS_MSG_IMAGE);
            massMessage.setMediaId(messageSend.getMediaId());
        } else if (messageSend.getType() == MaterialType.VOICE) {
            massMessage.setMsgType(WxConsts.MASS_MSG_VOICE);
            massMessage.setMediaId(messageSend.getMediaId());
        } else if (messageSend.getType() == MaterialType.VIDEO) {
            WxMpMaterialVideoInfoResult videoInfoResult = wxMpService.getMaterialService().materialVideoInfo(messageSend.getMediaId());
            // 把视频变成可被群发的媒体
            WxMpMassVideo video = new WxMpMassVideo();
            video.setTitle(videoInfoResult.getTitle());
            video.setDescription(videoInfoResult.getDescription());
            video.setMediaId(messageSend.getMediaId());
            WxMpMassUploadResult uploadResult = wxMpService.massVideoUpload(video);
            massMessage.setMsgType(WxConsts.MASS_MSG_VIDEO);
            massMessage.setMediaId(uploadResult.getMediaId());
        } else if (messageSend.getType() == MaterialType.NEWS) {
            WxMpMaterialNews materialNews = wxMpService.getMaterialService().materialNewsInfo(messageSend.getMediaId());
            WxMpMassNews news = new WxMpMassNews();
            for (WxMpMaterialNews.WxMpMaterialNewsArticle newsArticle : materialNews.getArticles()) {
                Response response = Http.get(newsArticle.getThumbUrl())
                    .header("Accept", "application/octet-stream")
                    .executeOrigin();
                String contentType = response.header("Content-Type");
                String fileType = MimeTypes.getDefaultMimeTypes().forName(contentType).getExtension();
                WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MEDIA_IMAGE, fileType.substring(1), response.body().byteStream());
                WxMpMassNews.WxMpMassNewsArticle article = new WxMpMassNews.WxMpMassNewsArticle();
                article.setTitle(newsArticle.getTitle());
                article.setContent(newsArticle.getContent());
                article.setThumbMediaId(uploadMediaRes.getMediaId());
                article.setShowCoverPic(newsArticle.isShowCoverPic());
                article.setAuthor(newsArticle.getAuthor());
                article.setContentSourceUrl(newsArticle.getContentSourceUrl());
                article.setDigest(newsArticle.getDigest());
                news.addArticle(article);
            }
            WxMpMassUploadResult massUploadResult = wxMpService.massNewsUpload(news);
            massMessage.setMsgType(WxConsts.MASS_MSG_NEWS);
            massMessage.setMediaId(massUploadResult.getMediaId());
        }
        massMessage.setSendAll(messageSend.isToAll());
        massMessage.setTagId(messageSend.getTagId());
        WxMpMassSendResult massResult = wxMpService.massGroupMessageSend(massMessage);
        return new ServiceResult<Boolean>()
            .setSuccess("0".equals(massResult.getErrorCode()))
            .setErrMessage(massResult.getErrorMsg());
    }
}
